<!--
 * @Descripttion:  
 * @version:  
 * @Author: chenxf
 * @Date: 2023-03-02 11:10:08
-->
<template>
  <a-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :bodyStyle="bodyStyle"
    style="top: 0px;"
    destroyOnClose
    :footer="null"
    cancelText="关闭"
    v-if="visible"
  >
    <!-- <a-spin :spinning="confirmLoading"> -->
    <div class="content-wrapper">
      <div class="content-left">
        <div class="process-name">
          <span>【{{ info.processName }}】版本列表</span>
        </div>
        <template v-if="!versionLoading">
          <div
            class="version-list"
            v-for="item in versionLists"
            :class="{ select: selectVersion.id == item.id }"
            @click="changeVersion(item)"
          >
            <a-tag color="blue"> 版本({{ item.version }}) </a-tag>
            <!-- <a-tag color="green" @click.stop="handleCopyVersion(item)" title="拷贝" style="cursor: pointer;">
              <a-icon type="copy" />
            </a-tag> -->
          </div>
        </template>
        <a-spin v-else class="spin-wrapper">
          <a-icon slot="indicator" type="loading" style="font-size: 30px" spin />
        </a-spin>
      </div>
      <div class="content-main" v-if="versionLists.length">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-item label="配置名称">
                  <a-input placeholder="请输入配置名称" v-model="queryParam.configName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                  <a-button type="primary" @click="addRow" icon="plus" style="margin-left: 8px">添加</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="tableLoading"
          @change="handleTableChange"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="editRow(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="showConditionConfigNodes(record)">人员配置</a>
            <a-divider type="vertical" />
            <a @click="showCopyModal(record)">拷贝配置</a>
            <a-divider type="vertical" />
            <a @click="deleteRow(record)">删除</a>
          </span>
        </a-table>
        <ProcessConditionConfigsFormModal
          ref="ProcessConditionConfigsFormModal"
          @ok="loadData"
          :deploymentId="selectVersion.deploymentId"
          :actProcessId="info.id"
        />
        <!-- 流程人员设置-->
        <ExtActProcessAssigneeModal
          v-if="assigneeVisible"
          :visible.sync="assigneeVisible"
          :info="info"
          :configId="processConditionConfigsRow.id"
          :deploymentId="selectVersion.deploymentId"
        ></ExtActProcessAssigneeModal>
      </div>
    </div>
    <a-modal
      v-model="visibleVersion"
      :title="'配置(' + processConditionConfigsRow.configName + ')拷贝至'"
      on-ok="handleOk"
    >
      <template slot="footer">
        <a-button key="back" @click="cancelVisible">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="saveCopyConfig">
          拷贝
        </a-button>
      </template>
      <a-table
        ref="table2"
        size="middle"
        bordered
        rowKey="id"
        :columns="configColumns"
        :dataSource="configDataSource"
        :pagination="confiIpagination"
        :loading="configLoading"
        :rowSelection="{ selectedRowKeys: selectedConfigRowKeys, onChange: onSelectChangeConfig }"
        @change="handleConfigTableChange"
      >
      </a-table>
    </a-modal>
  </a-modal>
</template>

<script>
import { httpAction, getAction, postAction, putAction, deleteAction } from '@/api/manage'
import ProcessConditionConfigsFormModal from './ProcessConditionConfigsFormModal.vue'
import ExtActProcessAssigneeModal from './ExtActProcessAssigneeModal.vue'
export default {
  name: 'ProcessConditionConfigsModal',
  components: { ProcessConditionConfigsFormModal, ExtActProcessAssigneeModal },
  props: {
    visible: Boolean,
    info: Object
  },
  data() {
    return {
      title: '流程条件配置',
      modalWidth: 1200,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      bodyStyle: {
        padding: '0',
        height: window.innerHeight - 80 + 'px'
      },
      confirmLoading: false,
      processKey: '',
      nodeList: '/act/process/extActProcessNodeDeployment/list',
      historyList: '/act/process/extActProcess/processDeploymentList',
      versionLists: [],
      selectVersion: {},
      extActProcessNode: '/act/process/extActProcessNode/list',
      deploymentNodeLists: [],
      selectDeploymentNode: {},
      form: {
        actEventType: 'TASK_CREATED',
        assigneeConditionConfig: '',
        assigneeTypeConfig: '',
        notifyAssignee: '',
        processConditionConfig: []
      },
      isEdit: false,
      rules: {},
      visibleVersion: false,
      copyVersionId: undefined,
      copyVersion: {},
      nodeLoading: false,
      versionLoading: false,
      isLoading: false,
      formLoading: false,
      visibleNode: false,
      copyNode: {},
      copyNodeId: [],
      duplicateAllAssigneeNode: false,
      duplicateAllAssignee: true,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '配置名称',
          align: 'center',
          dataIndex: 'configName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 260,
          scopedSlots: { customRender: 'action' }
        }
      ],
      tableLoading: false,
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      confiIpagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      dataSource: [],
      queryParam: {
        configName: ''
      },
      api: {
        processConditionConfigs: '/property/act/processConditionConfigs'
      },
      assigneeVisible: false,
      processConditionConfigsRow: {},
      selectionConfigRows: [],
      selectedConfigRowKeys: [],
      configLoading: false,
      configDataSource: [],
      configColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '配置名称',
          align: 'center',
          dataIndex: 'configName'
        }
      ]
    }
  },
  mounted() {
    this.getHistory()
  },
  methods: {
    close() {
      this.$emit('close')
      this.$emit('update:visible', false)
    },
    handleOk() {
      const that = this
      that.$emit('ok')
    },
    handleCancel() {
      this.close()
    },
    getHistory() {
      this.versionLoading = true
      getAction(this.historyList, { processKey: this.info.processKey }).then(res => {
        if (res.success) {
          this.versionLists = res.result.rows
          this.selectVersion = this.versionLists[0]
          if (this.versionLists.length) {
            this.deploymentId = this.versionLists[0].deploymentId
            this.versionLoading = false
            this.loadData()
          } else {
            this.nodeLoading = false
          }
        } else {
          this.$message.warning(res.message)
          this.versionLists = []
          this.nodeLoading = false
        }
        this.versionLoading = false
      })
    },
    getNodeHistory() {
      this.nodeLoading = true
      getAction(this.nodeList, { deploymentId: this.selectVersion.deploymentId }).then(res => {
        if (res.success) {
          this.deploymentNodeLists = res.result.rows
          this.selectDeploymentNode = this.deploymentNodeLists[0]
          this.getConfig()
        } else {
          this.$message.warning(res.message)
          this.deploymentNodeLists = []
        }
        this.nodeLoading = false
      })
    },
    getConfig() {
      const postData = {
        actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
        deploymentId: this.selectVersion.deploymentId,
        actProcessId: this.info.id,
        pageSize: 500
      }
      this.formLoading = true
      getAction('/act/processConditions', postData).then(res => {
        if (res.result.rows.length) {
          let form = res.result.rows[0]
          this.form = {
            ...form,
            processConditionConfig: form.processConditionConfig.map(i => {
              let tagName = undefined
              let tagParam = undefined
              try {
                let json = i.tag
                tagName = json.tagName
                tagParam = json.tagParam
              } catch (e) {}
              return { ...i, tagName, tagParam }
            })
          }
          this.isEdit = true
        } else {
          this.form = {
            actEventType: 'TASK_CREATED',
            assigneeConditionConfig: '',
            assigneeTypeConfig: '',
            notifyAssignee: '',
            processConditionConfig: []
          }
          this.isEdit = false
        }
        this.formLoading = false
      })
    },
    changeVersion(row) {
      this.selectVersion = row
      this.loadData()
    },
    changeDeploymentNode(row) {
      this.selectDeploymentNode = row
      this.getConfig()
    },
    // addRow() {
    //   this.form.processConditionConfig.push({
    //     column: undefined,
    //     name: undefined,
    //     require: true,
    //     tagName: undefined,
    //     tagParam: undefined
    //   })
    // },
    //提交
    submitEvent() {
      this.$refs.ruleForm.validate((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        } else {
          this.saveNodeConfig()
        }
      })
    },
    saveNodeConfig() {
      this.isLoading = true
      if (!this.isEdit) {
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId
        }
        postData.processConditionConfig = this.form.processConditionConfig.map(i => {
          let tag = undefined
          let config = {}
          try {
            config = JSON.parse(JSON.stringify(i))
            tag = {
              tagName: config.tagName,
              tagParam: config.tagParam
            }
            delete config.tagName
            delete config.tagParam
          } catch (e) {}
          return { ...config, tag }
        })
        console.log(postData)
        postAction('/act/processConditions', postData)
          .then(res => {
            if (res.success) {
              this.$message.success('保存成功')
              this.getConfig()
            } else {
              this.$message.error(res.message)
            }
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      } else {
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId,
          id: this.form.id
        }
        postData.processConditionConfig = this.form.processConditionConfig.map(i => {
          let tag = undefined
          let config = {}
          try {
            let config = JSON.parse(JSON.stringify(i))
            tag = {
              tagName: config.tagName,
              tagParam: config.tagParam
            }
            delete config.tagName
            delete config.tagParam
          } catch (e) {}
          return { ...config, tag }
        })
        putAction('/act/processConditions', postData).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.message)
          }
          this.isLoading = false
        })
      }
    },
    removeConfig(item) {
      let index = this.form.processConditionConfig.indexOf(item)
      if (index !== -1) {
        let _this = this
        this.$confirm({
          title: '',
          content: '确定删除该行?',
          onOk() {
            _this.form.processConditionConfig.splice(index, 1)
          },
          onCancel() {}
        })
      }
    },
    deleteNode() {
      let id = this.form.id
      if (!id) {
        this.$message.error('未有id')
        return
      }
      let _this = this
      this.$confirm({
        title: '删除节点流程条件配置',
        content: '确定删除节点流程条件配置?',
        onOk() {
          deleteAction('/act/processConditions/' + id).then(res => {
            if (res.success) {
              _this.$message.success('删除成功')
              _this.getConfig()
            } else {
              _this.$message.error(res.message)
            }
          })
        },
        onCancel() {}
      })
    },
    saveCopyConfig() {
      if (this.selectedConfigRowKeys.length == 0) {
        this.$message.error('未选择配置')
        return
      }
      putAction(
        this.api.processConditionConfigs +
          '/' +
          this.processConditionConfigsRow.id +
          '/duplicate/' +
          this.selectedConfigRowKeys.join()
      ).then(res => {
        if (res.success) {
          this.$message.success('拷贝成功')
          this.visibleVersion = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    cancelVisible() {
      this.visibleVersion = false
    },
    handleCopyVersion(row) {
      const postData = {
        actProcessId: this.info.id,
        deploymentId: row.deploymentId,
        pageSize: 500
      }
      getAction('/act/processConditions', postData).then(res => {
        if (res.result.rows.length) {
          this.visibleVersion = true
          this.copyVersion = row
        } else {
          this.$message.error('该流程无流程条件,无法拷贝')
        }
      })
    },
    handleCopyNode() {
      this.copyNode = this.selectDeploymentNode
      this.visibleNode = true
    },
    cancelVisibleNode() {
      this.visibleNode = false
    },
    saveCopyNode() {
      const postData = {
        actProcessId: this.info.id,
        targetDeploymentId: this.copyNode.deploymentId,
        deploymentId: this.copyNode.deploymentId,
        duplicateAllConfig: this.duplicateAllAssigneeNode,
        processNodeCodeMap: {}
      }
      postData.processNodeCodeMap[this.copyNode.processNodeCode] = this.copyNodeId
      putAction('/act/processConditions/duplicate', postData).then(res => {
        if (res.success) {
          this.$message.success('拷贝成功')
          this.visibleNode = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    loadData() {
      if (!this.selectVersion.deploymentId) {
        return
      }
      const postData = {
        deploymentId: this.selectVersion.deploymentId,
        actProcessId: this.info.id,
        pageSize: this.ipagination.pageSize,
        pageNo: this.ipagination.current,
        configName: this.queryParam.configName
      }
      this.tableLoading = true
      getAction(this.api.processConditionConfigs, postData)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.rows
            if (res.result.totalRows || res.result.total) {
              this.ipagination.total = res.result.totalRows || res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    editRow(record) {
      this.$refs.ProcessConditionConfigsFormModal.edit(record)
    },
    addRow(record) {
      this.$refs.ProcessConditionConfigsFormModal.add()
    },
    deleteRow(record) {
      var that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function() {
          that.tableLoading = true
          deleteAction(that.api.processConditionConfigs + '/' + record.id)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.error(res.message)
              }
            })
            .finally(() => {
              that.tableLoading = false
            })
        }
      })
    },
    searchReset() {
      this.queryParam.configName = ''
      this.ipagination.current = 1
      this.loadData()
    },
    searchQuery() {
      this.ipagination.current = 1
      this.loadData()
    },
    showConditionConfigNodes(record) {
      this.processConditionConfigsRow = record
      this.assigneeVisible = true
    },
    onSelectChangeConfig(selectedRowKeys, selectionRows) {
      this.selectedConfigRowKeys = selectedRowKeys
      this.selectionConfigRows = selectionRows
    },
    handleConfigTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      // if (Object.keys(sorter).length > 0) {
      //   this.isorter.column = sorter.field
      //   this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      // }
      this.confiIpagination = pagination
      this.loadConfigData()
    },
    loadConfigData() {
      this.configLoading = true
      const postData = {
        actProcessId: this.info.id,
        pageSize: this.confiIpagination.pageSize,
        pageNo: this.confiIpagination.current
      }
      getAction(this.api.processConditionConfigs, postData)
        .then(res => {
          if (res.success) {
            this.configDataSource = res.result.rows || res.result.records || res.result
            this.configDataSource = this.configDataSource.filter(i => {
              return i.id != this.processConditionConfigsRow.id
            })
            if (res.result.totalRows || res.result.total) {
              this.ipaginatconfiIpaginationion.total = res.result.totalRows || res.result.total
            } else {
              this.confiIpagination.total = 0
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.configLoading = false
        })
    },
    showCopyModal(record) {
      this.processConditionConfigsRow = record
      this.visibleVersion = true
      this.confiIpagination.current = 1
      this.loadConfigData()
    }
  }
}
</script>

<style lang="less" scoped>
.ant-modal-header {
  //padding: 0 !important;
}
// 兼容1.6.2版本的antdv全屏
/deep/ .ant-modal {
  top: 0;
  padding: 0;
}
.content-wrapper {
  display: flex;
  height: 100%;
  padding: 20px;
  .content-left {
    width: 240px;
    height: 100%;
    border-right: 1px solid #999;
    padding-right: 20px;
    overflow: auto;
  }
  .content-main {
    width: calc(100% - 240px);
    height: 100%;
    padding: 20px;
    overflow: auto;
    .form-footer {
      text-align: center;
    }
  }
  .spin-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .version-list {
    color: #000;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 40px;
    flex-wrap: wrap;
    padding: 4px;
    border-radius: 8px;
    gap: 6px;
    margin-bottom: 4px;
    cursor: pointer;
    &.select {
      background: #f1f2f4;
    }
    /deep/.ant-tag {
      scale: 0.88;
      margin-right: 2px;
    }
    .version-tag {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 21px;
      margin-left: 4px;
      font-weight: 500;
      color: #24b35f;
      background-color: #edfcf0;
      border: 1px solid #8ad7a7;
      border-radius: 4px;
      > span {
        scale: 0.85;
        font-size: 12px;
      }
    }
  }
  .process-name {
    height: 60px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    color: #33383e;

    span {
      position: relative;
      display: inline-flex;
    }
    // > ::after {
    //   border-bottom: 1px solid #33383e;
    //   width: 100%;
    //   height: 1px;
    //   content: '';
    //   display: inline-block;
    //   position: absolute;
    //   bottom: -4px;
    // }
  }
  .deployment-node {
    display: inline-flex;
    color: #7f8792;
    margin-right: 14px;
    cursor: pointer;
    &.select {
      color: #000;
      border-bottom: 1px solid;
    }
  }
  .deployment-node-wrapper {
    display: flex;
    .deployment-node-title {
      display: inline-flex;
      padding-right: 20px;
    }
  }
  .assignee-configs-form {
    padding: 20px 0;
    .table-tool {
      padding-bottom: 10px;
      > button {
        margin-right: 10px;
      }
    }
    .assignee-configs-form-tip {
      padding-top: 20px;
    }
  }
  .assignee-configs-form-inner {
    border: 1px solid #f1f2f4;
    .table-header {
      // padding: 20px;
      > .ant-col {
        padding: 20px 0;
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
    }
    .table-tr {
      border-top: 1px solid #f1f2f4;
      > .ant-col {
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
      .form-delete {
        position: absolute;
        left: 8px;
        top: 7px;
        font-size: 20px;
        cursor: pointer;
      }
    }
    // padding: 20px 0;
  }
}
</style>
